<?php
// +----------------------------------------------------------------------
// | MNsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2014~2023 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: 名牛云 <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2023-05-08 23:49
// +----------------------------------------------------------------------
namespace app\common\model;

use buwang\base\BaseModel;
use think\facade\Cache;

class Config extends BaseModel
{

    protected $pk = 'id';

    /**
     * @notes 存储引擎列表
     * @return array[]
     */
    public static function lists()
    {

        $default = self::getConfigData('storage', 'default', 'local');

        $data = [
            [
                'name' => '本地存储',
                'path' => '存储在本地服务器',
                'engine' => 'local',
                'status' => $default == 'local' ? 1 : 0
            ],
            [
                'name' => '七牛云存储',
                'path' => '存储在七牛云，请前往七牛云开通存储服务',
                'engine' => 'qnoss',
                'status' => $default == 'qnoss' ? 1 : 0
            ],
            [
                'name' => '阿里云OSS',
                'path' => '存储在阿里云，请前往阿里云开通存储服务',
                'engine' => 'alioss',
                'status' => $default == 'alioss' ? 1 : 0
            ]
        ];
        return $data;
    }

    /**
     * @notes 存储设置详情
     * @param $param
     * @return mixed
     * @author 段誉
     * @date 2022/4/20 16:15
     */
    public static function detail($param)
    {

        $default = static::getConfigData('storage', 'default', '');

        // 本地存储
        $local = ['status' => $default == 'local' ? 1 : 0];
        // 七牛云存储
        $qiniu = self::getConfigData('storage', 'qnoss', [
            'bucket' => '',
            'access_key' => '',
            'secret_key' => '',
            'domain' => '',
            'status' => $default == 'qnoss' ? 1 : 0
        ]);

        // 阿里云存储
        $aliyun = self::getConfigData('storage', 'alioss', [
            'bucket' => '',
            'access_key' => '',
            'secret_key' => '',
            'domain' => '',
            'status' => $default == 'alioss' ? 1 : 0
        ]);

        $data = [
            'local' => $local,
            'qnoss' => $qiniu,
            'alioss' => $aliyun,
        ];
        $result = $data[$param['engine']];
        if ($param['engine'] == $default) {
            $result['status'] = 1;
        } else {
            $result['status'] = 0;
        }
        return $result;
    }

    /**
     * @notes 设置存储参数
     * @param $params
     * @return bool|string
     */
    public static function setup($params)
    {
        if ($params['status'] == 1) { //状态为开启
            self::setConfigData('storage', 'default', $params['engine']);
        } else {
            self::setConfigData('storage', 'default', 'local');
        }

        switch ($params['engine']) {
            case 'local':
                self::setConfigData('storage', 'local', []);
                break;
            case 'qnoss':
                self::setConfigData('storage', 'qnoss', [
                    'qnoss_bucket' => $params['qnoss_bucket'] ?? '',
                    'qnoss_access_key' => $params['qnoss_access_key'] ?? '',
                    'qnoss_secret_key' => $params['qnoss_secret_key'] ?? '',
                    'qnoss_domain' => $params['qnoss_domain'] ?? ''
                ]);
                break;
            case 'alioss':
                self::setConfigData('storage', 'alioss', [
                    'alioss_bucket' => $params['alioss_bucket'] ?? '',
                    'alioss_access_key_id' => $params['alioss_access_key_id'] ?? '',
                    'alioss_access_key_secret' => $params['alioss_access_key_secret'] ?? '',
                    'alioss_endpoint' => $params['alioss_endpoint'] ?? '',
                    'alioss_domain' => $params['alioss_domain'] ?? '',
                ]);
                break;
        }

        Cache::delete('STORAGE_DEFAULT');
        Cache::delete('STORAGE_ENGINE');
        if ($params['engine'] == 'local' && $params['status'] == 0) {
            return 'default';
        } else {
            return true;
        }
    }

    /**
     * @notes 切换状态
     * @param $params
     */
    public static function change($params)
    {
        $default = Config::getConfigData('storage', 'default', '');
        if ($default == $params['engine']) {
            self::setConfigData('storage', 'default', 'local');
        } else {
            self::setConfigData('storage', 'default', $params['engine']);
        }
        Cache::delete('STORAGE_DEFAULT');
        Cache::delete('STORAGE_ENGINE');
    }


    /**
     * @notes 设置配置值
     * @param $type
     * @param $name
     * @param $value
     * @return mixed
     */
    public static function setConfigData(string $type, string $name, $value)
    {
        $original = $value;
        if (is_array($value)) {
            $value = json_encode($value, JSON_UNESCAPED_UNICODE);
        }

        $data = self::where(['type' => $type, 'name' => $name])->findOrEmpty();

        if ($data->isEmpty()) {
            self::create([
                'type' => $type,
                'name' => $name,
                'value' => $value,
            ]);
        } else {
            $data->value = $value;
            $data->save();
        }

        // 返回原始值
        return $original;
    }

    /**
     * @notes 获取配置值
     * @param $type
     * @param string $name 可为空【取某个类型下的所有name的值】
     * @param null $default_value
     * @return array|int|mixed|string
     */
    public static function getConfigData(string $type, string $name = '', $default_value = null)
    {
        if (!empty($name)) {
            $value = self::where(['type' => $type, 'name' => $name])->value('value');
            if (!is_null($value)) {
                $json = json_decode($value, true);
                $value = json_last_error() === JSON_ERROR_NONE ? $json : $value;
            }
            if ($value) {
                return $value;
            }
            // 返回特殊值 0 '0'
            if ($value === 0 || $value === '0') {
                return $value;
            }
            // 返回默认值
            if ($default_value !== null) {
                return $default_value;
            }
            // 返回本地配置文件中的值
            return config('bwsaas.' . $type . '.' . $name);
        }

        // 取某个类型下的所有name的值
        $data = self::where(['type' => $type])->column('value', 'name');
        foreach ($data as $k => $v) {
            $json = json_decode($v, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $data[$k] = $json;
            }
        }
        if ($data) {
            return $data;
        }
    }

}